package com.ad.pet.common.structure.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieSyncManager;

import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.ad.pet.App;
import com.ad.pet.R;
import com.ad.pet.common.data.injector.HasComponent;
import com.ad.pet.common.data.injector.HasPermission;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.structure.key.TokenKey;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.constant.Constant;
import com.ad.pet.utils.LyxUtils;
import com.just.agentweb.AgentWebConfig;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Cookie;
import okhttp3.HttpUrl;

/**
 * Created by ems on 2017/2/27.
 */

public abstract class BaseFragment extends Fragment {
    protected View mRootView;
    private BasePresenter mBasePresenter;
    protected Unbinder mBind;
    protected BaseFragment mFragment;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(initContentView(), container, false);
        initStatus();
        mBind = ButterKnife.bind(this, mRootView);
        return mRootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LyxUtils.changeAppLanguage(getActivity(), SpUtil.getInstance().getString(Constant.LANGUAGE,"cn"));
        initInjector();

        initViews();
        initData();
        initEvents();

        mBasePresenter = getPresenter();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragment = this;
    }

    protected abstract void initData();

    protected abstract void initEvents();

    protected abstract void initViews();

    public abstract void initInjector();

    public abstract int initContentView();

    protected abstract BasePresenter getPresenter();

    protected void initStatus() {
    }

    @Override
    public void onDestroy() {
        if (mBasePresenter != null) mBasePresenter.onDestroy();
        super.onDestroy();

    }

    @Override
    public void onDestroyView() {
        if (mBind != null) {
            mBind.unbind();
        }
        super.onDestroyView();
    }

    protected <T extends View> T findViewById(int id) {
        return (T) mRootView.findViewById(id);
    }


    @SuppressWarnings("unchecked")
    protected <C> C getComponent(Class<C> componentType) {
        return componentType.cast(((HasComponent<C>) getActivity()).getComponent());
    }

    protected RxPermissions getPermission() {
        return ((HasPermission) getActivity()).getPermission();
    }
    protected boolean hasLogin(){
        return !TextUtils.isEmpty(getAccessToken());
    }

    protected String getAccessToken(){
        return SpUtil.getInstance().getString(TokenKey.TOKEN);
    }

    /**
     * 将cookie同步到WebView
     */
    protected void syncCookie() {
//        AgentWebConfig.removeAllCookies();
//        AgentWebConfig.syncCookie(getString(R.string.ip_host),"");
//        AgentWebConfig.syncCookie(getString(R.string.ip_default),"");
        List<Cookie> cookies = (((PersistentCookieJar) App.getApp().getApplicationComponent().getOkHttpClient().cookieJar())).loadForRequest(HttpUrl.parse(getString(R.string.top_host)));
        StringBuffer sb = new StringBuffer();
        for (Cookie cookie : cookies) {
            String cookieName = cookie.name();
            String cookieValue = cookie.value();
            if (!TextUtils.isEmpty(cookieName)
                    && !TextUtils.isEmpty(cookieValue)&&TextUtils.equals(cookieName,"PHPSESSID")) {
                sb.append(cookieName + "=");
                sb.append(cookieValue + ";");
            }
        }
        sb.append("platform" + "=");
        sb.append("android" + ";");
//        sb.append("PHPSESSID" + "=");
//        sb.append(SpUtil.getInstance().getString(Constant.PHPSESSID) + ";");
        CookieSyncManager.createInstance(getActivity());
        AgentWebConfig.syncCookie(getString(R.string.top_host_point), sb.toString());
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName());
    }
}
